//
//  CourseViewController.m
//  jungoo
//
//  Created by Dang Quang Trung on 8/7/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "CourseViewController.h"
#import "Course.h"
#import "User.h"
#import "AppDelegate.h"


@implementation CourseViewController


@synthesize txtField = _txtField,segment = _segment;
@synthesize courseMode = _courseMode;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];    
}

#pragma mark - Private Method

- (void)onSetAutocompleteDataSource:(NSArray*)aDataSource
{
    autocompleteView.dataSource = aDataSource;
    autocompleteView.keyName = @"name";
    autocompleteView.delegate = self;
}

- (void)asyncLoadCourse
{
    if ([JGoUtility sharedCourses] == nil) {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
        
        dispatch_async(queue, ^{
            
            NSError *error = nil;
            NSArray *courses = [JGoAPI getCourses:&error];
            
            if (error) {
                LOG(@"%@",[error localizedDescription]);
            }
            else {
                
                [self performSelectorOnMainThread:@selector(onSetAutocompleteDataSource:) 
                                       withObject:courses 
                                    waitUntilDone:YES];
                [JGoUtility setCourses:[JGoUtility sharedCourses]];
            }
        });    
    }
    else {
        [self onSetAutocompleteDataSource:[JGoUtility sharedCourses]];
    }
}

- (NSInteger)indexForDegree:(NSString*)degree
{
    if ([degree isEqualToString:@"BA/BSc"]) {
        return 0;
    }
    
    if ([degree isEqualToString:@"Masters"]) {
        return 1;
    }
    
    if ([degree isEqualToString:@"Post Grad"]) {
        return 2;
    }
    
    return 0;
}

- (void)applyAppearance
{
    [self.navigationItem setHidesBackButton:YES];
    
    [self setBackButtonImageActiveName:nil 
                          inactiveName:@"back-button" 
                                target:self 
                                action:@selector(back:)];
    
    [self setRightButtonImageActiveName:nil 
                           inactiveName:@"done-button" 
                                 target:self 
                                 action:@selector(done:)];
    
    [self setTitle:@"Course"];
    [self.view setAutoresizesSubviews:NO];
    autocompleteView = [[AutocompleteView alloc] initWithFrame:CGRectMake(0, 112, 320, 371)];
    [self.view addSubview:autocompleteView];
    [_txtField setText:[[JGoUtility sharedCreateAccount] objectForKey:@"course"]];    
    [_txtField becomeFirstResponder];
    
    NSInteger indexDegree = [self indexForDegree:[[JGoUtility sharedCreateAccount] objectForKey:@"degree"]];
    [_segment setSelectedSegmentIndex:indexDegree];
}

- (NSString*)combineCourse
{
    if (_txtField.text.length) {
        return [NSString stringWithFormat:@"%@;%@",_txtField.text,
                [_segment titleForSegmentAtIndex:_segment.selectedSegmentIndex]];
    }
    else {
        return [NSString stringWithFormat:@";%@",[_segment titleForSegmentAtIndex:_segment.selectedSegmentIndex]];
    }
    
    return nil;
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];    
    [self applyAppearance];
    [self asyncLoadCourse];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return NO;
}

- (void)dealloc
{
    [dataSource release];
    [autoDataSource release];
    
    [super dealloc];
}

#pragma mark - Action

- (void)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)done:(id)sender
{
    if ([_txtField.text length]) {
        NSString *degree = [_segment titleForSegmentAtIndex:_segment.selectedSegmentIndex];
        NSString *courseName = _txtField.text;
        
        [[JGoUtility sharedCreateAccount] setValue:courseName ? courseName : @"" forKey:@"course"];
        [[JGoUtility sharedCreateAccount] setValue:degree forKey:@"degree"];
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    else {
        [Utility showAlert:@"Please enter your course."];
    }        
}

#pragma mark - TextField Delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    autocompleteView.hidden = NO;
    NSString *substring = [NSString stringWithString:textField.text];    
    substring = [substring stringByReplacingCharactersInRange:range withString:string];
    [autocompleteView searchAutocompleteEntriesWithSubstring:substring];
    
    return YES;
}

#pragma mark - AutocompleteView Delegate

- (void)autocompleteView:(AutocompleteView *)autocompleteView didSeletedWithString:(NSString *)aString
{
    _txtField.text = aString;
}

@end
